<template>
  <div class="seckill-page">
    <div class="activity-header">
      <h1>双11 限时秒杀</h1>
      <div class="countdown">
        <span class="time">{{ countdown }}</span>
      </div>
    </div>

    <div class="goods-list-container">
      <div
          v-for="seckillItem in allSeckillGoods"
          :key="seckillItem.id"
          class="goods-item"
      >
        <img
            :src="getGoodsImage(seckillItem.goods_id)"
            :alt="getGoodsName(seckillItem.goods_id)"
            class="goods-img"
            :class="{ 'out-of-stock': seckillItem.stock === 0 }"
        />
        <div v-if="seckillItem.stock === 0" class="sold-out-overlay">已售罄</div>

        <div class="goods-info">
          <h3 class="goods-name">{{ getGoodsName(seckillItem.goods_id) }}</h3>

          <div class="price-section">
            <span class="seckill-price">¥{{ seckillItem.seckill_price }}</span>
            <span class="original-price">¥{{ getGoodsPrice(seckillItem.goods_id) }}</span>
          </div>

          <div class="seckill-status">
            <div v-if="seckillItem.status === 0" class="not-started">
              <i class="el-icon-time"></i>
              即将开始
            </div>
            <div v-else-if="seckillItem.status === 1" class="ongoing">
              <i class="el-icon-time"></i>
              秒杀进行中
            </div>
            <div v-else-if="seckillItem.status === 2" class="sold-out">
              <i class="el-icon-circle-close"></i>
              已售空
            </div>
            <div v-else class="ended">
              <i class="el-icon-circle-close"></i>
              活动已结束
            </div>
          </div>

          <div class="seckill-button">
            <el-button
                type="danger"
                size="small"
                :disabled="seckillItem.stock <= 0 || seckillItem.status !== 1"
                @click="handleSeckill(seckillItem)"
            >
              {{ getButtonStatus(seckillItem) }}
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import seckillActivityApi from '@/api/seckill/seckillActivity_api.js'
import seckillGoodsApi from '@/api/seckill/seckillGoods_api.js'
import goodsApi from '@/api/goods_api.js'
import { ElMessage, ElProgress } from 'element-plus'
import { useRouter } from 'vue-router'

export default {
  name: 'ElevenSeckill',
  components: {
    ElProgress
  },
  data() {
    return {
      loading: true,
      error: '',
      allSeckillGoods: [],
      goodsInfoMap: new Map(),
      countdown: '加载中...',
      activity: null,
      isActivityActive: true,
      activityInfo: null
    }
  },
  mounted() {
    this.fetchSeckillData()
    this.startCountdown()
  },
  methods: {
    async fetchSeckillData() {
      try {
        this.loading = true
        this.error = ''

        // 获取活动信息（假设使用ID为1的活动）
        const activityResponse = await seckillActivityApi.getActivityById(1)
        if (activityResponse || activityResponse.data) {
          this.activityInfo = activityResponse
        }

        // 获取所有秒杀商品（直接使用后端返回的状态）
        const goodsResponse = await seckillGoodsApi.getSeckillGoodsList({})
        console.log('goodsResponse111', goodsResponse)

        if (goodsResponse || goodsResponse.data) {
          // 直接使用后端返回的数据，不修改状态
          this.allSeckillGoods = goodsResponse
          console.log('allSeckillGoods', this.allSeckillGoods)

          // 一次性获取所有相关商品信息
          await this.fetchAllGoodsInfo()
        }

        this.loading = false
      } catch (err) {
        this.error = '获取秒杀数据失败'
        this.loading = false
        console.error('获取秒杀数据失败:', err)
      }
    },

    async fetchAllGoodsInfo() {
      try {
        // 收集所有需要获取信息的商品ID
        const goodsIds = [...new Set(this.allSeckillGoods.map(item => item.goods_id))]
        console.log('需要获取信息的商品ID:', goodsIds)

        if (goodsIds.length > 0) {
          // 批量获取所有商品信息
          const promises = goodsIds.map(goodsId => goodsApi.getGoodsById(goodsId))
          const results = await Promise.allSettled(promises)

          // 处理所有返回结果
          results.forEach((result, index) => {
            const goodsId = goodsIds[index]
            try {
              if (result.status === 'fulfilled' || result.value || result.value.data) {
                this.goodsInfoMap.set(goodsId, result.value)
              }
            } catch (err) {
              console.error(`处理商品${goodsId}信息失败:`, err)
            }
          })
        }
      } catch (err) {
        console.error('批量获取商品信息失败:', err)
      }
    },

    getGoodsImage(goodsId) {
      const goodsInfo = this.goodsInfoMap.get(goodsId)
      return goodsInfo && goodsInfo.image ? goodsInfo.image : ''
    },

    getGoodsName(goodsId) {
      const goodsInfo = this.goodsInfoMap.get(goodsId)
      return goodsInfo ? goodsInfo.name : ''
    },

    getGoodsPrice(goodsId) {
      const goodsInfo = this.goodsInfoMap.get(goodsId)
      return goodsInfo ? goodsInfo.price : 0
    },

    getButtonStatus(item) {
      if (item.status === 0) return '即将开始'
      if (item.status === 2) return '已售空'
      if (item.status === 3) return '已结束'
      return '立即秒杀'
    },

    startCountdown() {
      // 倒计时逻辑（根据活动开始和结束时间计算）
      const updateCountdown = async () => {
        if (this.activityInfo) {
          const startTime = new Date(this.activityInfo.start_time).getTime()
          const endTime = new Date(this.activityInfo.end_time).getTime()
          const now = new Date().getTime()

          // 活动开始前：显示距离活动开始的倒计时
          if (now < startTime) {
            const diff = startTime - now
            const days = Math.floor(diff / (1000 * 60 * 60 * 24))
            const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
            const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))
            const seconds = Math.floor((diff % (1000 * 60)) / 1000)

            if (days > 0) {
              this.countdown = `距离活动开始 ${days}天 ${hours}小时 ${minutes}分钟`
            } else {
              this.countdown = `距离活动开始 ${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
            }

            // 更新活动状态为0（未开始）
            if (this.activityInfo.status !== 0) {
              try {
                await seckillActivityApi.updateStatus(this.activityInfo.id, 0)
                this.activityInfo.status = 0
              } catch (err) {
                console.error('更新活动状态失败:', err)
              }
            }

            // 更新所有秒杀商品状态为0（未开始）
            for (const item of this.allSeckillGoods) {
              if (item.status !== 0 && item.stock > 0) {
                try {
                  await seckillGoodsApi.updateSeckillGoods({...item, status: 0})
                  item.status = 0
                } catch (err) {
                  console.error(`更新商品${item.id}状态失败:`, err)
                }
              }
            }
          }
          // 活动进行中：显示距离活动结束的倒计时
          else if (now < endTime) {
            const diff = endTime - now
            const days = Math.floor(diff / (1000 * 60 * 60 * 24))
            const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
            const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))
            const seconds = Math.floor((diff % (1000 * 60)) / 1000)

            if (days > 0) {
              this.countdown = `距离活动结束 ${days}天 ${hours}小时 ${minutes}分钟`
            } else {
              this.countdown = `距离活动结束 ${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
            }

            // 更新活动状态为1（进行中）
            if (this.activityInfo.status !== 1) {
              try {
                await seckillActivityApi.updateStatus(this.activityInfo.id, 1)
                this.activityInfo.status = 1
              } catch (err) {
                console.error('更新活动状态失败:', err)
              }
            }

            // 更新所有秒杀商品状态为1（进行中），除非已售空
            for (const item of this.allSeckillGoods) {
              if (item.status !== 1 && item.status !== 2 && item.stock > 0) {
                try {
                  await seckillGoodsApi.updateSeckillGoods({...item, status: 1})
                  item.status = 1
                } catch (err) {
                  console.error(`更新商品${item.id}状态失败:`, err)
                }
              }
            }
          }
          // 活动已结束：显示活动已结束
          else {
            this.countdown = '活动已结束'
            this.isActivityActive = false

            // 更新活动状态为2（已结束）
            if (this.activityInfo.status !== 2) {
              try {
                await seckillActivityApi.updateStatus(this.activityInfo.id, 2)
                this.activityInfo.status = 2
              } catch (err) {
                console.error('更新活动状态失败:', err)
              }
            }

            // 更新所有秒杀商品状态为3（活动已结束），除非已售空
            for (const item of this.allSeckillGoods) {
              if (item.status !== 3 && item.status !== 2) {
                try {
                  await seckillGoodsApi.updateSeckillGoods({...item, status: 3})
                  item.status = 3
                } catch (err) {
                  console.error(`更新商品${item.id}状态失败:`, err)
                }
              }
            }
          }
        }
        setTimeout(updateCountdown, 1000)
      }

      updateCountdown()
    },

    handleSeckill(item) {
      if (item.status !== 1) {
        ElMessage.warning(
            item.status === 0 ? '秒杀活动尚未开始' :
                item.status === 2 ? '商品已售空' : '秒杀活动已结束'
        )
        return
      }

      if (item.stock <= 0) {
        ElMessage.warning('商品已售罄')
        return
      }

      // 跳转到秒杀订单页面
      this.$router.push(`/user/seckill/seckillOrderProfile/${item.id}`)
    }
  }
}
</script>

<style scoped>
.seckill-page {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding: 20px;
}

.activity-header {
  text-align: center;
  padding: 40px 20px;
  background: linear-gradient(to right, #ff4d4d, #ff8c00);
  color: white;
  border-radius: 8px;
  margin-bottom: 20px;
}

.activity-header h1 {
  font-size: 32px;
  margin-bottom: 20px;
}

.countdown {
  font-size: 18px;
}

.countdown .time {
  font-weight: bold;
  background: rgba(0, 0, 0, 0.2);
  padding: 5px 15px;
  border-radius: 20px;
}

.goods-list-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  padding: 20px 0;
}

.goods-item {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s;
  position: relative;
}

.goods-item:hover {
  transform: translateY(-5px);
}

.goods-img {
  width: 100%;
  height: 200px;
  object-fit: cover;
}

.goods-img.out-of-stock {
  filter: grayscale(100%);
}

.sold-out-overlay {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 10px 20px;
  border-radius: 4px;
  font-weight: bold;
  font-size: 18px;
}

.goods-info {
  padding: 15px;
}

.goods-name {
  font-size: 16px;
  font-weight: bold;
  margin: 0 0 10px 0;
  color: #333;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.price-section {
  margin-bottom: 15px;
}

.seckill-price {
  font-size: 20px;
  font-weight: bold;
  color: #ff4d4f;
  margin-right: 10px;
}

.original-price {
  font-size: 14px;
  color: #999;
  text-decoration: line-through;
}

.seckill-status {
  margin-bottom: 15px;
  padding: 8px;
  background: #f8f9fa;
  border-radius: 4px;
  text-align: center;
  font-size: 13px;
}

.seckill-status div {
  font-weight: bold;
}

.not-started {
  color: #1890ff;
}

.ongoing {
  color: #ff4d4f;
}

.sold-out {
  color: #faad14;
}

.ended {
  color: #999;
}

.seckill-button {
  text-align: center;
}

@media (max-width: 768px) {
  .goods-list-container {
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    gap: 15px;
  }

  .activity-header h1 {
    font-size: 28px;
  }

  .seckill-price {
    font-size: 18px;
  }
}
</style>
